<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="角色名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button icon="el-icon-search" type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button icon="el-icon-plus" type="primary" v-on:click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-popconfirm icon="el-icon-delete" title="确定删除吗？" @confirm="reallyChecked" style="margin-left: 5px;">
						<el-button slot="reference" type="danger">批量删除</el-button>
					</el-popconfirm>
					<!-- <el-button type="danger" v-on:click="batchDelete">批量删除</el-button> -->
				</el-form-item>

			</el-form>

		</el-col>

		<!--列表-->
		<template>
			<el-table :data="pageInfo.departments" highlight-current-row v-loading="loading" style="width: 100%;"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="100">
				</el-table-column>
				<el-table-column prop="name" label="角色名称" width="200" sortable>
				</el-table-column>
				<el-table-column prop="sn" label="唯一标识" width="200" sortable>
				</el-table-column>
				<el-table-column label="操作" width="350">
					<template scope="scope">
						<el-button type="success" size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-popconfirm icon="el-icon-delete" title="确定删除吗？" @confirm="handleDel(scope.row.id)"
							style="margin-left: 5px;">
							<el-button slot="reference" size="small" type="danger">删除</el-button>
						</el-popconfirm>
						<el-button type="success" size="small" @click="handleAuth(scope.row)">权限设置</el-button>
						<el-button type="success" size="small"  @click="setMenu(scope.row)">菜单设置</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>
		<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="this.query.pageNumber" :page-sizes="[5, 10, 20, 40]" :page-size=this.query.pageSize
			layout="total, sizes, prev, pager, next, jumper" :total=this.pageInfo.total>
		</el-pagination>

		<el-dialog title="授权" :visible.sync="authFormVisible" :close-on-click-modal="false">
			<el-form :model="rolePermission" label-width="80px" ref="form">
				<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
					@change="handleCheckAllChange">全选</el-checkbox>
				<div class="checkbox-table" v-for="(p, indexkey) in permissionTree" :key="p.sn">
					<template>
						<el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
							v-model='rolePermission.permissionSns' :label="p.sn" @change='handleCheck(1, indexkey)'>
							{{ p.name }}
						</el-checkbox>
						<div style="margin-bottom: 20px;">
							<div v-for="c in p.children" class="line-check" :key="c.sn"
								style="display: inline-block; margin-left: 20px;margin-bottom: 20px;">
								<el-checkbox class="check2" @change='handleCheck(2, indexkey)'
									v-model="rolePermission.permissionSns" :label="c.sn">
									{{ c.name }}
								</el-checkbox>
							</div>
						</div>
					</template>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="authFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveAuthSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>



		<el-dialog title="角色信息" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
			:close-on-press-escape="false" @close="cancel">
			<el-form :model="form">
				<el-form-item label="部门名字" :label-width="formLabelWidth">
					<el-input v-model="form.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="介绍" :label-width="formLabelWidth">
					<el-input v-model="form.sn" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="save">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog title="菜单设置" :visible.sync="menuFormVisible" :close-on-click-modal="false">
			<el-form :model="roleMenu" label-width="80px" ref="menuForm">
				<el-checkbox :indeterminate="isMenuIndeterminate" v-model="checkMenuAll"
					@change="handleCheckMenuAllChange">全选</el-checkbox>
				<div class="checkbox-table" v-for="(p, indexkey) in menuTree" :key="p.id">
					<template>
						<el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
							v-model='roleMenu.menuId' :label="p.id" @change='handleMenuCheck(1, indexkey)'>
							{{ p.name }}
						</el-checkbox>
						<div style="margin-bottom: 20px;">
							<div v-for="c in p.children" class="line-check" :key="c.id"
								style="display: inline-block; margin-left: 20px;margin-bottom: 20px;">
								<el-checkbox class="check2" @change='handleMenuCheck(2, indexkey)'
									v-model="roleMenu.menuId" :label="c.id">
									{{ c.name }}
								</el-checkbox>
							</div>
						</div>
					</template>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="menuFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveMenuSubmit">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>
<script>
//import NProgress from 'nprogress'
export default {
	data() {
		return {
			authFormVisible: false,
			rolePermission: {  // 授权对象
				permissionSns: []
			},
			isIndeterminate: false,
			checkAll: false,
			permissionTree: [],
			allPermissionSns: [],
			roleId:null,
			loading: false,
			addLoading: false,
			query: {
				pageNumber: 1,
				pageSize: 5,
				keyword: ''
			},
			pageInfo: {
				total: 0,
				departments: []
			},
			selectColumn: [],
			dialogFormVisible: false,
			form: {
				id: null,
				name: '',
				sn: ''
			},
			formLabelWidth: '120px',
			menuFormVisible:false,
			isMenuIndeterminate: false,
			checkMenuAll:false,
			menuTree:[],
			roleMenu:{
				menuId:[]
			},
			allMenus:[],
			roleForMenuId:null,
			menuForm: {
				id: null,
				name: '',
				url: '',
				icon:'',
				parent:{
					id:null,
					name:''
				},
				chileren:{
					id: null,
					name: '',
					url: '',
					icon:'',
				}
			},
		}
	},
	methods: {
		setMenu(row){
			this.roleForMenuId = row.id
			this.menuFormVisible = true;
			this.getMenuTree()
			this.queryAllMenuId()
			this.queryRoleMenu()
		},
		queryRoleMenu(){
			this.$http.post("/menu/"+this.roleForMenuId)
				.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.roleMenu.menuId = res.data.menusById
					}
				})
				.catch(res=>{
					this.$message({type:'warning',message:'网络异常'})
				})
		},

		saveMenuSubmit(){
			let data = {
				id:this.roleForMenuId,
				menuIds:this.roleMenu.menuId
			}
			this.$http.post('/role/menu',data)
				.then(res=>res.data).then(res=>{
					this.menuFormVisible = false
				})
		},
		handleCheckMenuAllChange(val){
			this.roleMenu.menuId = val ? this.allMenus : [];
        	this.isMenuIndeterminate = false;
		},
		handleMenuCheck(type, a = 0){
			// 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在

			let indexOf = this.roleMenu.menuId.indexOf(this.menuTree[a].id);
			if (type == 2) { // 二级菜单点击
				let index = 0;  //
				this.menuTree[a].children.map(item => {
					// 已选中的权限列表中，是否包含当前一级权限下的某个子权限
					if (this.roleMenu.menuId.indexOf(item.id) > -1) {
						index += 1;
					}
				})
				if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
					if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
						this.roleMenu.menuId.push(this.menuTree[a].id);
					}
				} else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
					if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
						this.roleMenu.menuId.splice(indexOf, 1);
					}
				}
			} else {  // 一级菜单点击
				if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
					this.menuTree[a].children.map(item => {
						if (this.roleMenu.menuId.findIndex((n) => n == item.id) < 0) {
							this.roleMenu.menuId.push(item.id)
						}
					})
				} else {
					// 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
					this.menuTree[a].children.map(item => {
						if (this.roleMenu.menuId.findIndex((n) => n == item.id) > -1) {
							this.roleMenu.menuId.splice(this.roleMenu.menuId.findIndex((n) => n == item.id), 1);
						}
					})
				}
			}
			// 获取已选中的长度
			let checkedCount = this.roleMenu.menuId.length;
			// 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
			this.checkMenuAll = checkedCount === this.allMenus.length;
			// 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
			this.isMenuIndeterminate = checkedCount > 0 && checkedCount < this.allMenus.length;
		},
		getMenuTree(){
			this.$http.get('/menu')
				.then(res=>res.data).then(res=>{
					if (res.code == 200) {
						this.menuTree = Object.assign({}, res.data.menus);
					}else{
						this.$message({type:'warning',message:'网络异常2'})
					}
				})
				.catch(res=>{
					this.$message({type:'warning',message:'网络异常1'})
				})
		},
		queryAllMenuId(){
			this.$http.get('/menu/menuId')
				.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.allMenus = res.data.menuIds
					}
				})
		},
		

		saveAuthSubmit(){
			let data = {
				id:this.roleId,
				permissionSns:this.rolePermission.permissionSns
			}
		
			this.$http.post('/role/permission',data)
			.then(res=>res.data).then(res=>{
				if(res.code == 200){
					this.authFormVisible = false
				}
			})
		},
		queryallPermissionSns(){
			this.$http.get("/permission/sns")
            .then(res=>res.data).then(res=>{
				if(res.code == 200){
					this.allPermissionSns = res.data.permissionSns
				}
			})
		},
		handleCheckAllChange(val) {
			this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
        	this.isIndeterminate = false;
		},
		handleAuth(row) {
			this.roleId = row.id
			this.authFormVisible = true
			this.queryallPermissionSns()

			this.getPermissionTree()
			this.getRoleIdPermission()
		},
		getRoleIdPermission(){
			this.$http.post('/role/'+this.roleId)
				.then(res=>res.data).then(res=>{
					this.rolePermission.permissionSns = res.data.RolePermission
				})
		},
		getPermissionTree(){
			this.$http.get("/permission")
				.then(res=>res.data).then(res=>{
					if(res.code == 200){
						this.permissionTree = res.data.permissions
					}else{
						this.$message({ message: "网络异常", type: 'success' });
					}
				})
				.catch(res=>{
					this.$message({ message: "网络异常", type: 'success' });
				})
		},
		handleCheck(type, a = 0) { // 多选框
			// 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在

			let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
			if (type == 2) { // 二级菜单点击
				let index = 0;  //
				this.permissionTree[a].children.map(item => {
					// 已选中的权限列表中，是否包含当前一级权限下的某个子权限
					if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
						index += 1;
					}
				})
				if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
					if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
						this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
					}
				} else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
					if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
						this.rolePermission.permissionSns.splice(indexOf, 1);
					}
				}
			} else {  // 一级菜单点击
				if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
					this.permissionTree[a].children.map(item => {
						if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
							this.rolePermission.permissionSns.push(item.sn)
						}
					})
				} else {
					// 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
					this.permissionTree[a].children.map(item => {
						if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
							this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
						}
					})
				}
			}
			// 获取已选中的长度
			let checkedCount = this.rolePermission.permissionSns.length;
			// 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
			this.checkAll = checkedCount === this.allPermissionSns.length;
			// 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
		},
		//编辑取消方法
		cancel() {
			this.dialogFormVisible = false
			this.getRoles()
		},
		//编辑按钮触发事件
		handleEdit(row) {

			let temp = Object.assign({}, row);
			this.form = temp
			this.dialogFormVisible = true

		},

		//添加信息按钮触发事件
		handleAdd() {
			this.form = {
				name: '',
				intro: '',
			}
			this.dialogFormVisible = true
		},
		//保存信息网络请求
		save() {
			this.$http.post('/role', this.form)
				.then(res => {
					//console.log(res);
					if (res.data.code == 200) {
						this.dialogFormVisible = false
						this.$message({ message: res.data.message, type: 'success' });
						this.getRoles();
					} else {
						this.$message({ message: res.data.message, type: 'danger' });
					}
				}).catch(res => {
					this.$message({ message: '网络异常', type: 'error' });
				})
		},
		reallyChecked() {
			var ids = this.selectColumn.map(x => x.id);
			if (ids.length == 0) {
				this.$message({ message: '未选中消息', type: 'warning' });
				//return ;
			} else {
				this.batchDelete(ids)
			}
		},
		//批量删除
		batchDelete(ids) {
			//var ids = this.selectColumn.map(x => x.id);
			this.$http.patch("/role/", ids)
				.then(res => {
					console.log(res);
					if (res.data.code == 200) {
						this.$message({ message: '删除成功', type: 'success' });
						this.query.pageNumber = 1
						this.getRoles();
					} else {
						this.$message({ message: '请联系管理员!', type: 'warning' });
					}
				}).catch(res => {
					this.$message({ message: '糟糕糟糕偶买噶，魔法怎么失灵了', type: 'warning' });
				})

		},

		handleSelectionChange(val) {
			console.log(val);
			this.selectColumn = val
		},
		handleDel(id) {
			console.log(id);
			this.$http.delete("/role/" + id)
				.then(res => {
					console.log(res);
					if (res.data.code == 200) {
						this.$message({ message: '删除成功', type: 'success' });
						this.query.pageNumber = 1
						this.getRoles();
					} else {
						this.$message({ message: '请联系管理员!', type: 'danger' });
					}
				}).catch(res => {
					this.$message({ message: '糟糕糟糕偶买噶，魔法怎么失灵了', type: 'warning' });
				})

		},

		search() {
			this.query.pageNumber = 1;
			this.getRoles();
		},
		handleSizeChange(val) {
			this.query.pageSize = val;
			this.query.pageNumber = 1;
			this.getRoles();
		},
		handleCurrentChange(val) {
			this.query.pageNumber = val;
			this.getRoles();
		},
		//获取部门列表
		getRoles() {
			this.$http.put('/role', this.query)
				.then(res => res.data).then(res => {
					if (res.code == 200) {
						this.pageInfo.departments = res.data.data.rows
						this.pageInfo.total = res.data.data.total
					}
				})
				.catch(res => {
					console.log(res);
				})
		}
	},
	mounted() {
		this.getRoles();
	}
};

</script>

<style scoped></style>